package com.webchat.netty.server.handler;

import com.webchat.common.constants.NettySocketConstants;
import com.webchat.common.util.IDGenerateUtil;
import com.webchat.common.util.JsonUtil;
import com.webchat.domain.vo.dto.mall.im.NettyServerMessageDTO;
import com.webchat.netty.server.rocketmq.producer.RocketMQProducer;
import com.webchat.netty.server.service.UserChannelManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.producer.SendResult;


@Slf4j
public class NettyWebSocketMessageHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame req) throws Exception {

        // 处理ws数据帧
        TextWebSocketFrame textWebSocketFrame = (TextWebSocketFrame) req;
        String message = textWebSocketFrame.text();

        log.info("netty server read msg:{}", message);

        if (StringUtils.equals(message, "ping")) {
            ctx.writeAndFlush(new TextWebSocketFrame("ok"));
            return;
        }
        NettyServerMessageDTO clientMessage = JsonUtil.fromJson(message, NettyServerMessageDTO.class);
        clientMessage.setMsgId(IDGenerateUtil.createId("IM"));
        clientMessage.setMsgTime(System.currentTimeMillis());
        clientMessage.setRead(false);
        String clientMessageJson = JsonUtil.toJsonString(clientMessage);
        log.info("Netty Chat WebSocket Connection Received message: {}", clientMessageJson);
        SendResult sendResult = RocketMQProducer.send("netty_server_chat_msg", "im_chat", clientMessageJson);
        log.info("Netty Server Chat Message Send to MQ Finished ===> sendResult: {}", sendResult);
    }

    /**
     * 链接创建
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("Netty Chat WebSocket Connection Active！");
    }


    /**
     * 链接断开
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        log.info("Netty Chat WebSocket Connection Inactive！");
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        log.info("Netty Chat WebSocket Connection Exp！", cause);
    }

    private String getConnectionUserId(ChannelHandlerContext ctx) {

        Object userIdObj = ctx.channel().attr(AttributeKey.valueOf(NettySocketConstants.QUERY_USER_ID)).get();
        return userIdObj == null ? null : userIdObj.toString();
    }

    private String getConnectionBizCode(ChannelHandlerContext ctx) {

        Object bizCodeObj = ctx.channel().attr(AttributeKey.valueOf(NettySocketConstants.QUERY_BIZ_CODE)).get();
        return bizCodeObj == null ? null : bizCodeObj.toString();
    }
}
